package com.cc.screen;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class TxtToExcelConverter {
    private static final Logger log = LogManager.getLogger(TxtToExcelConverter.class);

    public static void convertTxtToExcel(String txtFilePath, String excelFilePath) throws IOException {
        Workbook workbook = new HSSFWorkbook();
        Sheet sheet = workbook.createSheet("Data");

        List<String[]> rows = readTxtFile(txtFilePath);
        int rowNum = 0;

        for (String[] rowData : rows) {
            Row row = sheet.createRow(rowNum++);
            int colNum = 0;
            for (String field : rowData) {
                Cell cell = row.createCell(colNum++);
                cell.setCellValue(field);
            }
        }

        try (FileOutputStream outputStream = new FileOutputStream(excelFilePath)) {
            workbook.write(outputStream);
        }
    }

    private static List<String[]> readTxtFile(String txtFilePath) throws IOException {
        List<String[]> rows = new ArrayList<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(txtFilePath))) {
            String line;
            int count =0;

                while ((line = reader.readLine()) != null) {
                    String[] cells = line.split("name="); // Assuming comma-separated values
                    try {
                        String[] lastCell = new String[3];
                        lastCell[0] = cells[0].substring(0,cells[0].length()-2);
                        lastCell[1] = cells[1].substring(0, cells[1].length() - 50).trim();
                        lastCell[2] = cells[1].substring(cells[1].length() - 50, cells[1].length()).trim();
                        rows.add(lastCell);
                        count++;
                    }catch (Exception ex){
                        System.out.println(count);
                    }
                }

        }
        return rows;
    }

    public static void main(String[] args) {
        try {
            convertTxtToExcel("E:\\aa.txt", "E:\\output.xlsx");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}